<?php
declare(strict_types=1);

namespace App\Admin\Controllers\Exam;

use App\Admin\Actions\Exam\BindCollectionAction;
use App\Admin\Controllers\BaseController;
use App\Library\MiniWeChatClient;
use App\Library\SnowFlakeId;
use App\Logic\Com\UserFileUploadService;
use App\Model\Admin\Exam\AdminCategory;
use App\Model\Admin\Exam\AdminCollection;
use EasyWeChat\Kernel\Http\StreamResponse;
use Encore\Admin\Form;
use Encore\Admin\Grid;

/**
 * @project: 兔兔考试系统
 * @author: Mandy
 * @date: 2023/7/17
 * @link: https://www.tutudati.com/
 * @site: 微信搜索-兔兔考试系统
 */
class CollectionController extends BaseController
{
    protected $title = "试卷管理";

    public function grid(): Grid
    {
        $grid = new Grid(new AdminCollection());
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->like('title', "试卷名称");
                $filter->equal('is_show', "上架状态")->select([
                    1 => '上架',
                    2 => '下架',
                ]);
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->between('created_at', "创建时间")->datetime();
                $filter->equal('recommend', "是否推荐")->select([
                    1 => '是',
                    2 => '否',
                ]);
            });
        });
        $grid->model()->orderByDesc("id")->paginate(10);
        $grid->column("uid", "数据编号")->copyable();
        $grid->column("cover", "试卷封面")->lightbox(['width' => 100, 'height' => 100]);
        $grid->column("mini_qr_code", "小程序码")->lightbox(['width' => 100, 'height' => 100]);
        $grid->column("category.title", "试卷类目");
        $grid->column("title", "试卷名称")->editable();
        $grid->column("author", "试卷作者")->editable();
        $grid->column("time", "试卷时长")->time();
        $grid->column("year", "试卷年份");
        $grid->column("sort", "显示权重")->integer();
        $grid->column('is_show', "上架状态")->switch($this->switch);
        $grid->column('is_free', "是否免费")->switch($this->isFree);
        $grid->column('recommend', "是否推荐")->switch($this->rec);
        $grid->column("level", "试卷难度")->radio([1 => "简单", 2 => "中等", 3 => "较难"]);
        $grid->column("submit", "答题人数")->sortable();
        $grid->column("collection", "收藏人数")->sortable();
        $grid->column("created_at", "创建时间");
        $grid->disableExport();
        $grid->actions(function ($actions) {
            $actions->disableView();
            $actions->add(new BindCollectionAction());
        });
        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new AdminCollection());
        $form->hidden("uid", "试卷编号")->default(SnowFlakeId::getId());
        $form->hidden("url", "图片地址")->default(env("QINIU_URL"));
        $form->image("path", "试卷封面")->uniqueName()->required();
        $form->select("category_uid", "试卷类目")->options(AdminCategory::getList())->required();
        $form->text("title", "试卷名称")->rules('required|max:255')->help("最大长度不可超过255。");
        $form->textarea("remark", "试卷描述")->rules('required|max:64')->help("最大不可超过64个字符。");
        $form->text("author", "试卷作者")->rules('required|max:20');
        $form->time("time", "试卷时长")->required();
        $form->year("year", "试卷年份")->default(date("Y"))->required()->help("不确定年份，默认为当前年份");
        $form->number("sort", "显示权重")->default(0)->help("值越大，显示权重越高");
        $form->switch("is_show", "上架状态")->states($this->switch)->default(1);
        $form->switch("is_free", "是否免费")->states($this->isFree)->default(2);
        $form->switch("recommend", "是否推荐")->states($this->rec)->default(1);
        $form->radio("level", "试卷难度")->options([1 => "简单", 2 => "中等", 3 => "较难"])->default(1)->required();
        $form->multipleImage("picture", "试卷配图")->sortable()->removable();
        $form->UEditor('content', "试卷说明")->options(['initialFrameHeight' => 400])->required();
        $form->saved(function (Form $form) {
            try {
                $uid = $form->uid;
                $response = MiniWeChatClient::client()->app_code->getQrCode("/subpages/exam/collection/detail?uid=" . $uid, 300);
                if ($response instanceof StreamResponse) {
                    $fileSaveName = SnowFlakeId::getId() . 'appcode.png';
                    $response->saveAs(public_path(), $fileSaveName);
                    $uploadImageInfo = UserFileUploadService::imageUploadByPath(public_path() . "/" . $fileSaveName);
                    $form->model()->update(["mini_qr_code" => $uploadImageInfo["url"]], ["uid" => $uid]);
                    unlink(public_path() . "/" . $fileSaveName);
                }
            } catch (\Exception $exception) {
                var_dump($exception->getMessage());
                die;
            }
        });

        return $form;
    }
}
